package com.myproject.controller;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myproject.model.SysUser;
import com.myproject.service.SysUserService;
import com.myproject.utils.PasswordUtil;

@Controller
public class MainController {

	@Autowired
	private SysUserService sysUserService;
	
	@RequestMapping("/")
	@ResponseBody
	public String index(){
		return "hello world";
	}
	
	@RequestMapping("/test")
	@ResponseBody
	public String test(){
		return "test";
	}
	
	@RequestMapping("/login")
	public String login(){
		return "login";
	}
	
	@RequestMapping("/profile")
	@ResponseBody
	public Principal profile(Principal principal){
		System.out.println(SecurityContextHolder.getContext().getAuthentication().getName());
		return principal;
	}
	
	@RequestMapping("/user")
	public String user(HttpServletRequest request){
		return "user";
	}
	
	@RequestMapping("/register")
	public String register(HttpServletRequest request){
		String username = request.getParameter("username_register");
		String password = request.getParameter("password_register");
		if(username == null || password == null){
			return "register";
		}
		if("".equals(username) || "".equals(password)){
			request.setAttribute("message", "用户名或密码不能为空");
			return "register";
		}
		username = username.trim();
		password = password.trim();
		if(sysUserService.findSysUserByUsername(username) != null){
			request.setAttribute("message", "用户已存在");
			return "register";
		}
		SysUser user = new SysUser();
		user.setUsername(username);
		user.setPassword(PasswordUtil.getMD5(password));
		sysUserService.registerSysUser(user);
		request.setAttribute("message", "注册成功");
		return "register";
	}
}
